#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include "logger.h"

#define BUFSIZE 256

int get_temperature(float *temp)
{
	int               fd;
	char              buf[BUFSIZE];
	char              *ptr = NULL;
	DIR               *dirp = NULL;
	struct dirent     *direntp = NULL;
	char              w1_path[64] = "/sys/bus/w1/devices/";
	char              chip_sn[32];
	int               found = 0;
	char              ds18b20_path[64];


	dirp = opendir(w1_path);
	if(NULL == dirp)
	{
		log_error("Opendir() folder [%s] failure : %s\n", w1_path, strerror(errno));
		return -1;
	}
	
	while( NULL != (direntp=readdir(dirp)) )
	{
		if( strstr(direntp->d_name,"28-"))
		{
				strncpy(chip_sn,direntp->d_name,sizeof(chip_sn));
				found = 1;
		}
	}

	closedir(dirp);

	if(!found)
	{
		log_warn("can not found ds18b20 chipset\n");
		return -1;
	}
	snprintf(ds18b20_path,sizeof(ds18b20_path),"%s%s/w1_slave",w1_path,chip_sn);
	
	fd = open(ds18b20_path,O_RDONLY); 
	if(fd < 0)
	{
		log_error("open file failure: %s\n",strerror(errno));
		return -1;
	}

	memset(buf,0,sizeof(buf));
	if( read(fd, buf, sizeof(buf)) <0 )
	{
		log_debug("Read data from fd = %d file failure : %s\n", fd, strerror(errno));
		return -1;
	}

	ptr = strstr(buf, "t=");
	if( NULL == ptr )
	{
		log_warn("can not find 't=' string\n");
		return -1;
	}
	
	ptr += 2;
	*temp = atof(ptr)/1000;
	close(fd);

	return 0;
}
